<template>
	<div class="cloneContainer">
		<a-menu v-if="pojectInfo.template == 1" style="background: transparent;min-width: 0;margin-bottom: 20px" v-model:selectedKeys="menus.currentId" mode="horizontal" :items="[{label: t('control', '全部'), key: ''}, ...menus.structure]" @select="show" />
		<div class="header">
			<a-input v-model:value="searchData['search_AND_LIKE_student.name']" autocomplete="off"
			:placeholder="t('control', '请输入学生姓名')" style="width:280px;margin-right: 12px" />
			<div>
				<a-button type="primary" @click="(pagination.current=1,tableData=[],show())">{{t('control', '查询')}}</a-button>
				<a-button style="margin-left: 10px" @click="(pagination.current=1,searchData = {},show())">{{t('control', '重置')}}</a-button>
			</div>
		</div>
		<div class="header" style="margin-top: 20px;">
			<div></div>
			<!-- <minMenu v-model="menus.currentId" :structure="menus.structure" jump="none" inline @handleMenuClick="show" /> -->
			<div style="display: flex;white-space: nowrap;">
				<a-button v-if="pojectInfo.template == 0" style="margin-left: 20px" @click="handleClick({ name: '加入成员', record, index })">{{t('control', '加入成员')}}</a-button>
				<div v-else>
					<a-button style="margin-left: 20px" @click="handleClick({ name: '加入成员', record, index })">{{t('control', '加入成员')}}</a-button>
					<a-button  v-if="pojectInfo.template == 1" style="margin-left: 10px" @click="handleClick({ name: '创建小组', record, index })">{{t('control', '创建小组')}}</a-button>
				</div>
			</div>
		</div>
		<div class="content">
			<div style="flex:1;min-height: 0;overflow: auto;">
				<a-table
					:key="activeName"
					:dataSource="tableData" :columns="columns" :pagination="false">
					<template #bodyCell="{ column, text, record, index }">
						<template v-if="column.dataIndex === 'studentName'">
							<span>
								{{ text }}<a-tag style="margin-left: 10px;" color="success" v-if="record.leader">{{t('control', '小组组长')}}</a-tag>
							</span>
						</template>
						<template v-if="column.dataIndex === 'projectName'">
							<a-tooltip placement="topLeft">
								<template #title>
									<span>{{ text }}</span>
								</template>
								<span style="display: inline-block; max-width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
									{{ text }}
								</span>
							</a-tooltip>
						</template>
						<template v-if="column.key === 'operate'">
							<a style="margin-left: 12px" @click="handleClick({ name: '编辑', record, index })">{{t('common', '编辑')}}</a>
							<a-popconfirm :title="t('common', '确定移除吗？')" @confirm="handleClick({ name: '移除', record, index })">
								<a style="margin-left: 12px; color: #ff454a">{{t('common', '移除')}}</a>
							</a-popconfirm>
						</template>
					</template>
				</a-table>
			</div>
			<a-pagination style="text-align: center" @change="show" v-model:current="pagination.current" show-size-changer  v-model:pageSize="pagination.size"
				:total="pagination.totalElements" />
		</div>

		<a-modal :maskClosable="false" style="top: 200px;" v-model:open="groupModelVisible" @ok="handleMemberClick({name: '确定创建小组'})">
      <div style="padding-top: 30px">
        <div style="display: flex;align-items: center;margin-top: 10px;" v-if="pojectInfo.template == '1'">
          <div style="margin-right: 20px;width: 70px;">{{t('modal', '组名')}}</div>
          <a-input v-model:value="groupData.projectTeamName" :placeholder="t('common', '请输入')"></a-input>
        </div>
        <div style="display: flex;align-items: center;margin-top: 10px;">
          <div style="margin-right: 20px;width: 70px;" class="required">{{t('modal', '岗位')}}</div>
          <a-select v-model:value="groupData.projectJobId" style="width: 100%;" :placeholder="t('common', '请选择')">
            <a-select-option :value="item.id" v-for="item in projectJobList">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div style="display: flex;align-items: center;margin-top: 10px;">
          <div style="margin-right: 20px;width: 70px;" class="required">{{t('modal', '学号')}}</div>
          <a-input v-model:value="groupData.num" :placeholder="t('common', '请输入')"  @blur="handleBlur"></a-input>
        </div>
        <div style="display: flex;align-items: center;margin-top: 10px;margin-bottom: 20px;">
          <div style="margin-right: 20px;width: 70px;" class="required">{{t('modal', '姓名')}}</div>
          <a-input v-model:value="groupData.name" :placeholder="t('common', '请输入')"></a-input>
        </div>
      </div>
		</a-modal>
    <a-modal :maskClosable="false" style="top: 200px;" v-model:open="moberModelVisible" @ok="handleMemberClick({name: '确定创建成员'})">
      <div style="padding-top: 30px">
				<div style="display: flex;align-items: center;margin-top: 10px;" v-if="pojectInfo.template == '1'">
          <div style="margin-right: 20px;width: 70px;" class="required">{{t('modal', '小组编号')}}</div>
          <!-- <a-input v-model:value="moberData.projectTeamId" :placeholder="t('common', '请输入小组编号')"></a-input> -->
					<a-select v-model:value="moberData.projectTeamId" style="width: 100%;" :placeholder="t('common', '请选择')">
            <a-select-option :value="item.key" v-for="item in menus.includingZeroStructure">{{item.key}} {{ item.label }}</a-select-option>
          </a-select>
        </div>
        <div style="display: flex;align-items: center;;margin-top: 10px;">
          <div style="margin-right: 20px;width: 70px;" class="required">{{t('modal', '岗位')}}</div>
          <a-select v-model:value="moberData.projectJobId" style="width: 100%;" :placeholder="t('common', '请选择')">
            <a-select-option :value="item.id" v-for="item in projectJobList">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div style="display: flex;align-items: center;;margin-top: 10px;">
          <div style="margin-right: 20px;width: 70px;" class="required">{{t('modal', '学号')}}</div>
          <a-input v-model:value="moberData.num" :placeholder="t('common', '请输入')"  @blur="handleBlur1"></a-input>
        </div>
        <div style="display: flex;align-items: center;margin-top: 10px;margin-bottom: 20px;">
          <div style="margin-right: 20px;width: 70px;" class="required">{{t('modal', '姓名')}}</div>
          <a-input v-model:value="moberData.name" :placeholder="t('common', '请输入')"></a-input>
        </div>
      </div>
		</a-modal>


		<a-modal v-model:open="infoModal.visible"
			:footer='null'>
			<a-form
				style="padding-top: 30px"
				ref="infoModalRef"
				:model="infoModal.model"
				:rules="infoModal.rules"
				:label-col="{ style: { width: '120px' } }"
				@finish="editMessage"
			>
				<a-form-item has-feedback :label="t('modal', '姓名')" name="studentName">
					<a-input :disabled="true"  v-model:value="infoModal.model.studentName" autocomplete="off" />
				</a-form-item>
				<a-form-item has-feedback :label="t('modal', '学号')" name="studentNum" >
					<a-input :disabled="true" v-model:value="infoModal.model.studentNum" autocomplete="off" />
				</a-form-item>
				<a-form-item has-feedback :label="t('modal', '年级')" name="year">
					<a-input :disabled="true" v-model:value="infoModal.model.year" autocomplete="off" />
				</a-form-item>
				<a-form-item has-feedback :label="t('modal', '手机号')" name="mobile">
					<a-input :disabled="true" v-model:value="infoModal.model.mobile" autocomplete="off" />
				</a-form-item>
				<a-form-item has-feedback :label="t('modal', '岗位')" name="newProjectJobId">
					<a-select v-model:value="infoModal.model.newProjectJobId" style="width: 100%;" :placeholder="t('projectDetail','请选择岗位')">
            <a-select-option :value="item.id" v-for="item in projectJobList">{{ item.name }}</a-select-option>
          </a-select>
				</a-form-item>
				<a-form-item has-feedback :label="t('modal', '小组编号')" name="newTeamId" v-if="pojectInfo.template == '1'">
					<!-- <a-input  v-model:value="infoModal.model.newTeamId"  /> -->
					<a-select v-model:value="infoModal.model.newTeamId" style="width: 100%;" :placeholder="t('common','请选择')">
            <a-select-option :value="item.key" v-for="item in menus.includingZeroStructure">{{ item.key }} {{ item.label }}</a-select-option>
          </a-select>
				</a-form-item>

				<a-form-item>
					<a-button style='float: right;' type="primary" @click="handleInfoSubmit">{{ t('common','保存') }}</a-button>
					<a-button style="float: right;margin-right: 10px" @click="()=>infoModal.visible=flase">{{ t('common','取消') }}</a-button>
				</a-form-item>
			</a-form>
    </a-modal>
	</div>
</template>
<script setup>
import { reactive, ref, watch, inject } from 'vue'
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import minDatePicker from '@/components/common/minDatePicker.vue'
import { myProjectStudentPage, teacherRemove, findProjectJobs, studentCheck, teacherAddStudent, teacherEditStudent, studentSignedProject } from '@/request/process/member'
import { message, Modal } from 'ant-design-vue'
import minMenu from '@/components/common/minMenu.vue'
import { findTeamByProject } from '@/request/process/examine'
import { t } from '@/i18n'

const searchData = ref({})
const pagination = ref({ totalElements: 0, current: 1, size: 10 })
const formModel = ref({})
const formRef = ref()
const modal = reactive({ visible: false, formDisable: false, name: '' })
const menus = reactive({ currentId: '', structure: [] })

const rules = {
	newProjectJobId: [
		{ required: true, message: '请选择', trigger: 'change', },
	],
	newTeamId: [
		{ required: true, message: '请输入', trigger: 'change', },
	],
}
const infoModalRef = ref()
const infoModal = reactive({
	visible: false,
	formRef: null,
	model: {},
	rules: {
		name: [
			{ required: true, message: t('common','请输入'), trigger: 'change', },
		],
	},
})
const originColumns = [

	{ title: t('table', '学生姓名'), dataIndex: 'studentName', key: 'studentName' },
	{ title: t('table', '学号'), dataIndex: 'studentNum', key: 'studentNum' },
	{ title: t('table', '班级'), dataIndex: 'className', key: 'className' },
	{ title: t('table', '岗位名称'), dataIndex: 'projectJobName', key: 'projectJobName' },
	{ title: t('table', '操作'), dataIndex: 'operate', key: 'operate' },
]
const columns = ref([...originColumns])
const tableData = ref([])
const activeName = ref('已加入')
const conutGroup = ref({})

let pojectInfo = JSON.parse(sessionStorage.getItem('pojectInfo') || '{}')
const projectJobList = ref({})



const groupShow = async () => {

	let res = {
		小组编号分组: await findTeamByProject({projectId: pojectInfo.id, })
  }
	if (res['小组编号分组']) {
		menus.structure = res['小组编号分组'].data.map(item => ({ ...item, label: item.teamName || `${item.leaderName || ''}${t('common', '组')}`, key: item.teamId })).filter(val => val.memberNumber)
		menus.includingZeroStructure = res['小组编号分组'].data.map(item => ({ label: item.teamName || `${item.leaderName || ''}${t('common', '组')}`, key: item.teamId }))
		menus.currentId = ['']
	}
}
const firstShow = async () => {
	if (pojectInfo.template == '1') {
		columns.value.splice(2,0,	{ title: t('table', '组名'), dataIndex: 'teamName', key: 'teamName' })
		columns.value.splice(3,0,	{ title: t('table', '小组编号'), dataIndex: 'teamId', key: 'teamId' })
	}
	let res = {
    jobs: await findProjectJobs(pojectInfo.id),

  }
	if (res['jobs']) projectJobList.value = res['jobs'].data
	groupShow()
}
const show = async () => {
	let req = {
		...pagination.value,
		page: pagination.value.current - 1,
		...searchData.value,
		projectId: pojectInfo.id,
		// 'search_AND_EQ_project.studentProjects.projectTeamId': menus.currentId[0]
		'search_AND_EQ_projectTeamId': menus.currentId[0]
	}
	let res = {
		列表: await myProjectStudentPage(req),
  }
	if (res['列表']) {
		tableData.value = res['列表'].data.content
		pagination.value = {
			...pagination.value,
			...res['列表'].data.page
		}
	}
}
(async () => {
	await firstShow()
	show()
})()

const classStructure = ref([])

const selectedRowKeys = ref([])
const onSelectChange = keys => selectedRowKeys.value = keys

const groupModelVisible = ref(false)
const groupData = ref({})
const moberModelVisible = ref(false)
const moberData = ref({})
const getStudentProjectInfo = async ({name, num}) => {
	let sRes = await studentCheck({name, num})
	if(!sRes) return
	let otherRes = await studentSignedProject({studentId: sRes?.data?.id || ''})
	return otherRes?.data
}
const handleClick = async ({ name, record }) => {
	let req = {
		...record
	}, res = null, operate = null, info = null
	switch (name) {

		case '移除':
			info = await getStudentProjectInfo({name: record.studentName, num: record.studentNum})
			if (info.projectList) {
				operate = await new Promise((resolve, reject) => {
					Modal.confirm({
						content: `${record.studentName}存在"${(info.projectList.map(val => val.projectName).join())}"项目，确认将他移除`,
						onOk() {
							resolve(true);
						},
						confirmText: t('common','确定'),
						cancelText: t('common','取消'),
						onCancel() {
							resolve(false);
						},
					})
				})
				if (!operate) return
			}
			
			res = await teacherRemove({studentId: req.studentId, projectJobId: req.projectJobId})
			if (!res) return
			operate = await new Promise((resolve, reject) => {
				Modal.info({
					content: t('projectCard','请及时通知学生重新选取项目'),
					onOk() {
						resolve(true);
					},
					confirmText: t('common','确定'),
				})
			})
			message.success(t('common','操作成功'))
			pagination.value.current = 1
			show()
			break
		case '加入成员':
		groupShow()
      moberData.value = {}
      moberModelVisible.value = true
      break
    case '创建小组':
      groupData.value = {}
      groupModelVisible.value = true
      break
		case '编辑':
			infoModal.visible = true
			infoModal.model = {...record, newProjectJobId: record.projectJobId, newTeamId: record.teamId}
			console.log(infoModal)
			break
	}
}

const handleMemberClick = async ({ name, record, index }) => {
	console.log(record, '?')
	let res = null, otherRes = null, req = {}, operate = null
	switch (name) {
		case '确定创建成员':
			if (!moberData.value.name || !moberData.value.num || !moberData.value.projectJobId) return message.error(t('common','请输入'))
			if (pojectInfo.template == 1 && !moberData.value.projectTeamId) return message.error(t('common','请输入'))
			res = await studentCheck({name: moberData.value.name, num: moberData.value.num})
      if(!res) return
			otherRes = await studentSignedProject({studentId: res?.data?.id || res?.data || ''})
			if (otherRes.data.total && otherRes.data?.limit && otherRes.data?.total >= otherRes.data?.limit) {
				return message.error(`${t('table','学生姓名')}：${moberData.value.name}、${t('table','学号')}：${moberData.value.num}，${t('control','已加入')}：${otherRes.data?.total || ''} ${t('control','最多加入')}：${otherRes.data?.limit || ''}, ${t('control','可报名项目数量已达到要求上限，无法添加进入该项目')}`)
				// return message.error(`学生姓名：${.value.name}、学号：${moberData.value.num}，可报名项目数量已达到要求上限，无法添加进入该项目`)
				// operate = await new Promise((resolve, reject) => {
				// 	Modal.confirm({
				// 		title: '不符合要求的学生教师强制报名提示',
				// 		content: `学生${moberData.value.name}、学号：${moberData.value.num}不满足该项目${pojectInfo.name}(年级/班级/参与项目数量等）要求，是否强制将该学生加入项目？`,
				// 		onOk() { resolve(true) },
				// 		confirmText: '确定',
				// 		cancelText: '取消',
				// 		onCancel() { resolve(false) },
				// 	})
				// })
				// if (!operate) return
			}
			res = await teacherAddStudent({projectJobId: moberData.value.projectJobId || '', projectTeamId: moberData.value.projectTeamId || '', studentId: res?.data?.id || res?.data || ''})
			if (!res) return
			message.success(t('control','添加成功'))
			await show()
			moberModelVisible.value = false
			break
		case '确定创建小组':

		if (!groupData.value.name || !groupData.value.num || !groupData.value.projectJobId) return message.error(t('common','请输入'))
			res = await studentCheck({name: groupData.value.name, num: groupData.value.num})
      if(!res) return
			otherRes = await studentSignedProject({studentId: res?.data?.id || res?.data || ''})
			if (otherRes.data.total && otherRes.data?.limit && otherRes.data?.total >= otherRes.data?.limit) return message.error(`${t('table','学生姓名')}：${res.data.name}、${t('table','学号')}：${res.data.num}，${t('control','已加入')}：${otherRes.data?.total || ''} ${t('control','最多加入')}：${otherRes.data?.limit || ''}, ${t('control','可报名项目数量已达到要求上限，无法添加进入该项目')}`)

			res = await teacherAddStudent({projectJobId: groupData.value.projectJobId || '', studentId: res?.data?.id || res?.data || '', projectTeamName: groupData.value.projectTeamName || ''})
			if (!res) return
			message.success(t('control','添加成功'))
			await show()
			groupModelVisible.value = false
			break
	}
}

const handleBlur = async () => {
	if (!groupData.value.num) return message.error(t('control','请输入学号'))
	let res = await studentCheck({num: groupData.value.num})
	if(!res) return
	groupData.value.name = res.data.name
}
const handleBlur1 = async () => {
	if (!moberData.value.num) return message.error(t('control','请输入学号'))
	let res = await studentCheck({num: moberData.value.num})
	if(!res) return
	moberData.value.name = res.data.name
}


const handleInfoSubmit = async () => {
	let v = await infoModalRef.value.validate().catch(err => false)
	if (!v) return
	// let info = await getStudentProjectInfo({name: infoModal.model.studentName, num: infoModal.model.studentNum})
	// if (info.projectList) {
	// 	let operate = await new Promise((resolve, reject) => {
	// 		Modal.confirm({
	// 			content: `${record.studentName}存在"${(info.projectList.map(val => val.projectName).join())}"项目，确认将他移除`,
	// 			onOk() {
	// 				resolve(true);
	// 			},
	// 			confirmText: '确定',
	// 			cancelText: '取消',
	// 			onCancel() {
	// 				resolve(false);
	// 			},
	// 		})
	// 	})
	// 	if (!operate) return
	// }
			
	let req = {
		userId: infoModal.model.studentId,
		newProjectJobId: infoModal.model.newProjectJobId,
		newTeamId: infoModal.model.newTeamId || '',
	}
	let res = await teacherEditStudent(req)
	if (!res) return
	infoModal.visible = false
	message.success(t('common',"操作成功"))
	show()
}
const handleExport = async () => {
	if (!selectedRowKeys.value.length) return message.info(t('common','请选择'))
}


</script>

<style lang="scss" scoped>
$mainColor: #a84e91;

.cloneContainer {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: white;
		border-radius: 10px;
		height: 80px;
		padding: 20px;
		.item {
			cursor: pointer;
			margin-right: 15px;
			padding: 5px 10px;
			border: 1px solid transparent;
		}
		.activeItem {
			border-radius: 10px;
			/* border: 1px solid $mainColor; */
			box-shadow: $generalBoxShadow;
		}
	}

	.content {
		margin-top: 20px;
		padding: 20px;
		overflow: auto;
		flex: 1;
		display: flex;
		flex-direction: column;
		background: white;
		border-radius: 10px;
		
	}
}


.required {
    position: relative;
    /* padding-left: 30rpx; */
}
.required::before {
    content: '*';
    font-size: 16px;
    color: red;
    position: absolute;
    top: 0;
    bottom: 0;
    left: -10px;
    margin: auto;
    display: flex;
    align-items: center;
}
</style>